<template>
    <el-container>
        <el-header style="height: 70px;">
            <el-row class="header">
                <h2>欢迎：{{ userinfo.userName }}</h2>
            </el-row>
            <el-row class="header">
                <el-col :span="14" class="mainstyle">
                    <p>商品 余额:{{ userinfo.balance }}</p>
                </el-col>
                <el-col :span="10" class="mainstyle">
                    <p>购物车:{{ total }}元</p>
                </el-col>
            </el-row>
        </el-header>
        <el-main>
            <el-row>
                <el-col :span="14" class="mainstyle">
                    <el-scrollbar height="100%" wrap-style="overflow-x: hidden;">
                        <el-input v-model="itemToBeSearch" placeholder="输入要搜索的商品" @input="findItem()"/>
                        <div v-for="product in itemToBeSearchList" :key="product.id" class="card">
                            <div class="picture">
                                <p>商品图片</p>
                            </div>
                            <div class="name">
                                <p>{{ product.name }}</p>
                            </div>
                            <div class="jobtitle">
                                <p>{{ product.price }}元</p>
                            </div>
                            <div class="buttons">
                                <button class="cart-button" @click="addToCart(product)">加入购物车</button>
                            </div>
                        </div>
                    </el-scrollbar>
                </el-col>
                <el-col :span="10" class="mainstyle">
                    <el-scrollbar height="100%">
                        <div v-for="item in cart" :key="item.id" class="cart-item" @click="removeFromCart(item)">
                            <h3>{{ item.name }}</h3>
                            <p>数量: {{ item.quantity }}</p>
                            <p>价格: {{ item.price }}</p>
                        </div>
                    </el-scrollbar>
                </el-col>
            </el-row>
        </el-main>
        <el-footer>
            <el-row>
                <el-col :span="4">
                    <el-button type="primary" class="backbtn" @click="backtologin()">返回</el-button>
                </el-col>
                <el-col :span="20">
                    <el-button type="primary" class="calres" @click="shopComfirmWindowCheck()">结算</el-button>
                </el-col>
            </el-row>
        </el-footer>
    </el-container>
    <el-dialog v-model="shopComfirmWindow" title="确认购买" width="60%">
        <el-row>
            <img :src="imageSrc" alt="Captured Image" v-if="imageSrc" style="width: 100%;"/>
            <video style="width: 100%;" ref="videoRef" v-if="!imageSrc" autoplay></video>
        </el-row>
        <br/>
        <el-row justify="center">
            <el-col :span="6">
                <el-button type="primary" :disabled="ConfirmBtnDisabled" @click="settlement()">确认购买</el-button>
            </el-col>
        </el-row>
    </el-dialog>
</template>

<script>
import { readBuilderProgram } from 'typescript'
import { reactive, onMounted, toRefs, ref} from 'vue'
  // @ts-ignore
import { useStore } from '../store'
import { useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import apiSet from '../plugins/dbApi'

export default {
    setup(){
        const route = useRouter()
        const store = useStore()
        const videoRef = ref(null)

        const data = reactive({
            products: [
                { id: 1, name: 'A1', price: 10 },
                { id: 2, name: 'B2', price: 20 },
                { id: 3, name: 'C3', price: 30 },
                { id: 4, name: 'A4', price: 10 },
                { id: 5, name: 'B5', price: 20 },
                { id: 6, name: 'C6', price: 30 },
            ],
            cart: [],
            total: 0,
            userinfo: store.getUserInfo,
            imageSrc: null,
            imgBlob: null,
            videoStream: null,
            shopComfirmWindow: false,
            ConfirmBtnDisabled: false,
            itemToBeSearch: '',
            itemToBeSearchList : [
                { id: 1, name: 'A1', price: 10 },
                { id: 2, name: 'B2', price: 20 },
                { id: 3, name: 'C3', price: 30 },
                { id: 4, name: 'A4', price: 10 },
                { id: 5, name: 'B5', price: 20 },
                { id: 6, name: 'C6', price: 30 },
            ],
        })
        const method = reactive({
            addToCart: (product) => {
                const cartItem = data.cart.find(item => item.id === product.id)
                if (cartItem) {
                    cartItem.quantity++;
                } else {
                    data.cart.push({ ...product, quantity: 1 })
                }
                data.total = data.cart.reduce((acc, item) => acc + item.price * item.quantity, 0);
            },
            removeFromCart: (item) => {
                const index = data.cart.findIndex(cartItem => cartItem.id === item.id)
                if (index !== -1) {
                    data.cart[index].quantity--
                    if (data.cart[index].quantity === 0) {
                        data.cart.splice(index, 1);
                    }
                    data.total = data.cart.reduce((acc, item) => acc + item.price * item.quantity, 0); 
                }
            },
            backtologin: () => {
                store.resetUserInfo()
                route.push('/')
            },
            shopComfirmWindowCheck: () => {
                if(data.total === 0){
                    ElMessage({
                        type: 'error',
                        message: '购物车为空',
                    })
                    return
                } else {
                    if (!data.userinfo.userName) {
                        ElMessage({
                            type: 'error',
                            message: '用户未登录',
                        });
                        return;
                    }
                }
                data.shopComfirmWindow = true
                method.startVideo()
            },
            settlement: async () => {
                if(data.total > data.userinfo.balance){
                    ElMessage({
                        type: 'error',
                        message: '余额不足',
                    })
                }else{
                    data.ConfirmBtnDisabled = true
                    await method.capturePhoto()
                    apiSet.settlement(data.userinfo, data.cart, data.imageSrc).then(res => {
                        ElMessage({
                            type: 'success',
                            message: '购买成功',
                        })
                        apiSet.refreshUserInfo(data.userinfo.cardNumber).then((res) => {
                            if(res.status === 500){
                                ElMessage({
                                    type: 'error',
                                    message: '用户信息获取失败',
                                })
                                route.push('/')
                            } else {
                                data.ConfirmBtnDisabled = false
                                data.shopComfirmWindow = false
                                data.userinfo = store.getUserInfo
                                data.cart = []
                                data.total = 0
                            }
                        })
                    })
                }
            },
            findItem: () => {
                if(data.itemToBeSearch === ''){
                    data.itemToBeSearchList = data.products
                } else {
                    data.itemToBeSearchList = data.products.filter(item => item.name.includes(data.itemToBeSearch))
                }
            },
            startVideo : async () => {
                try {
                    data.imageSrc = null;
                    data.videoStream = await navigator.mediaDevices.getUserMedia({ video: true });
                    if (videoRef.value) {
                        videoRef.value.srcObject = data.videoStream;
                    }
                } catch (error) {
                    console.error("Error accessing webcam: ", error);
                }
            },
            capturePhoto() {
                if(data.videoStream == null){
                    method.startVideo()
                    return
                }
                const video = videoRef.value;
                const canvas = document.createElement("canvas");
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;
                const context = canvas.getContext("2d");
                context.drawImage(video, 0, 0, canvas.width, canvas.height);
                data.imageSrc = canvas.toDataURL("image/png");
                method.stopVideo();
            },
            stopVideo() {
                if (data.videoStream) {
                    data.videoStream.getTracks().forEach(track => track.stop());
                    data.videoStream = null;
                }
            }
        })
        return {
            ...toRefs(data),
            ...toRefs(method),
            videoRef,
        }
    }
}
</script>

<style scoped>
    @import '../assets/css/shop.css';
</style>